<?php
/*
 *  supplier 供货商添加类
 *
 *  @param $c 一般是类名
 *  @param $a 一般是方法名
 */
class goods extends Admin {

    // private $tab = array( 'goodsEdit' => '宝贝编辑', 'goodsTask' => '宝贝任务');
    private $prePicAddr = "content/attachment/prePic";
    private $postPicAddr = "content/attachment/postPic";
    private $unzipPicAddr = "content/attachment/unzipPic";
    private $unzipPostPicAddr = "content/attachment/unzipPostPic";
    private $zipPicAddr = "content/attachment/zipPic";
    private $goodsHtmlAddr = "content/goodsHtml";
    private $goodsNo = '';
    private $pagePicInfo='';
    private $thickness = array('薄','稍薄','厚度适中','稍厚','厚');
    private $flexAttr = array('无弹','微弹','弹性适中','弹力','超弹');
    private $goodsRight =array('宝贝定价'=>1,'自然属性'=>2,'宝贝原图'=>3,'宝贝命名'=>4,'宝贝尺寸'=>5,'原图下载'=>6,'处理后图片'=>7,'PS图下载'=>8,'宝贝描述'=>9);
    private $goodsStatus = array('初始态','已定价','已编辑属性','已上传原图','已命名','已编辑尺寸','图片处理中','图片已PS','PS图已下载','宝贝属性页生成');
    private $texture = array('柔软','偏软','适中柔软度','偏硬');
    private $style = array('宽松','合身','修身','紧身');
    private $clothStyle = array( '其他','运动','淑女', '休闲', '酷炫','卡通','图案', '韩派' );
    private $picType = array('小熊','米老鼠','豹纹','长格');
    private $brand = array( '其他','巴拉巴拉','小猪班纳','笛莎', '巴布豆', '红孩儿','韩版' );
    private $clothType = array('全部','上衣', '卫衣/绒衫', '毛衣/针织衫', '羽绒服/棉服', '短袖T恤', '裙子', '吊带衫/背心',
        '裤子',  '牛仔裤', '冬棉裤');


    public function index( $c, $a ) {
        $this->table = 'bsInfo';

        $where = '';

        $result = $this->Paged()->findAll(null );

        $pager = $result[ 'page' ];
        $result = $result[ 'result' ];

        foreach($result as $val)
        {
            $val['goodsStatus'] = $this->goodsStatus[$val['goodsStatus']];
        }


        include $this->display( $c );
    }

    public function  search($c,$a)
    {
        $this->table = 'bsInfo'; // 数据库表名

        $where = array( G( 'k' ) => G( 'v' ) );
        if ( $key = G( 'key' ) ) {
            $tmp = '';
            foreach ( $where as $k => $v ) {
                $tmp .= "{$k}='" . urldecode( $v ) . "' and ";
            }
            $where = $tmp ? ( $tmp . "goodsNo ={$key} " ) : '';
        }

        $result = $this->Paged()->findAll( $where );
        $pager = $result[ 'page' ];
        $result = $result[ 'result' ];

        foreach($result as $val)
        {
            $val['goodsStatus'] = $this->goodsStatus[$val['goodsStatus']];
        }


        include $this->display( $c ); // 加载模板
    }
    public function edit( $c, $a ) {
        if ( !$id = intval( G( 'id' ) ) ) {
            $this->error();
            exit;
        }

        $this->table = ''; // 数据库表名
        $result = $this->find( array( 'id' => $id ) ); // 查找数据
        include $this->display( $c ); // 加载模板
    }

    public function editAttr( $c, $a)
    {

        $goodsNo = intval( G( 'goodsNo' ));

        $condition = array('goodsNo'=>$goodsNo);
        $this->table = 'natureAttr';
        $this->pk = 'goodsNo';
        $result = $this->find($condition);

        include $this->display( $c );
    }
    public function editOrigPic($c, $a)
    {
        $goodsNo = intval( G( 'goodsNo' ));

        $condition = array('goodsNo'=>$goodsNo);
        $this->table = 'natureAttr';
        $this->pk = 'goodsNo';
        $result = $this->find($condition);



        if(isset($result))
        {
            $result = array('goodsNo'=>$goodsNo);
        }

        print_r($result);
        include $this->display( $c );
    }
    public function editPrice($c, $a)
    {
        $result = array('goodsNo'=>G( 'goodsNo' ));
        include $this->display( $c );
    }

    public function editGoodsName($c, $a)
    {
        $goodsNo = intval( G( 'goodsNo' ));
        $result = array('goodsNo'=>$goodsNo);
        include $this->display( $c );
    }
    public function editClothSize($c, $a)
    {
        $goodsNo = intval( G( 'goodsNo' ));
        $result = array('goodsNo'=>$goodsNo,'t'=>intval( G( 't',1 )));


        $this->table = 'bsInfo';
        $res = $this->find(array('goodsNo'=>$goodsNo),null,'size');

        $res = explode(',',$res['size']);

        include $this->display( $c );
    }
    public function editPostPic($c, $a)
    {
        $goodsNo = intval( G( 'goodsNo' ));
        $result = array('goodsNo'=>$goodsNo);
        include $this->display( $c );
    }
    public function downLoadPics($c, $a)
    {
        $result = array('goodsNo'=>G('in_id'));
        $addr = $this->zipPicAddr;
        $fileName = date("Y-M-D").".zip";

        include $this->display( $c );
    }

    public function editOnSaleDes($c, $a)
    {
        $goodsNo = intval( G( 'goodsNo' ));
        $templateId = 1;
        $this->table = 'templateInfo';
        $result1 = $this->findAll(array('templateId'=> $templateId,'pagePicFlag'=>true),'pagePosition',"pagePicName");

        for($i = 0; $i <count($result1); $i++ )
        {

            $result[$i] = $result1[$i]['pagePicName'];
        }

        print_r($result);

        include $this->display( $c );
    }
    private function unzip( $zipFile )
    {
        $zip = new ZipArchive();
        $res = $zip->open( $zipFile );
        if ( $res !== true ) {
            $zip->close();
            return '系统错误:' . $res;
        }

        $msg = $zip->extractTo( WEBROOT . 'content/unzip/' ) ? true : '解压文件失败!';
        $zip->close();
        return $msg;

    }
    public function  updateGoodsStatus($goodsNo,$status)
    {
        $this->table = 'bsInfo';
        $rows['goodsStatus'] = $status;

        $goodsNo = trim($goodsNo);

        $this->pk = 'id';
        print_r($goodsNo);
        print_r($status);

        $msg = $this->update( array('goodsNo'=>$goodsNo), $rows ) ? 'success' : 'failed';  //更新供货商
    }



    public function saveEditAttr( $c, $a ) {
        # 获取表单数据

        //print_r($_POST);
        foreach ( $_POST as $key => $val ) {

            $rows[ $key ] = htmlspecialchars( trim( $val ) );

        }

        # 注意 表单字段必须跟数据库表字段名一样
        $this->table = 'natureAttr'; // 数据库表名
        $this->pk = 'goodsNo';

        if ( $id = $this->find(  array('goodsNo' => $rows[ 'goodsNo' ])) ) {
            $msg = $this->update( array( 'goodsNo' => $id['goodsNo'] ), $rows ) ? 'success' : 'failed';  //更新供货商
        } else {
            $msg = $this->create( $rows ) ? 'success' : 'failed';                         // 添加供货商
        }

        unset($rows);
        $rows['goodsNo'] = $_POST['goodsNo'];
        $rows['goodsStatus'] = 1;                    //'1':宝贝编辑
        $rows['idNatureAttr'] = $_SESSION['userId'];


        $this->updateGoodsStatus($rows['goodsNo'],$this->goodsRight['自然属性']);

        /**zouhong-edit**/
        //  $rows['dateNatureAttr'] = date("Y-M-d");
        /**zouhong-edit-end**/

        $this->table = 'goodsEdit';
        $rows['idNatureAttr'] = $this->admin['id'];
        $rows['dateNatureAttr'] = date("Y-M-D");
        $this->pk = 'goodsNo';

        print_r("2547");

        if ( $id = $this->find(  array('goodsNo' => $rows[ 'goodsNo' ])) ) {
            $msg = $this->update( array( 'goodsNo' => $id['goodsNo'] ), $rows ) ? 'success' : 'failed';  //更新供货商
        } else {
            $msg = $this->create( $rows ) ? 'success' : 'failed';                         // 添加供货商
        }

        exit( $msg );
    }



    public function saveEditOrigPic( $c, $a ) {


        /****
         *  1.获取上传文件信息，并保存到服务器
         *  2.更新宝贝编辑表，将原图上传的时间以及处理人的信息记录到此表中。
         *  3.更新基本信息表，将原图的地址存入数据库.
         ***/


        /****
         *  STEP1.获取上传文件信息，并保存到服务器
         ***/
        foreach ( $_POST as $key => $val ) {
            $rows[ $key ] = htmlspecialchars( trim( $val ) );
        }

        $rows[ 'dateline' ] = strtotime( $rows[ 'dateline' ] );
        unset( $rows[ 'attach' ] );

        print_r($_FILES);

        echo "Type: " . $_FILES["prePicfile"]["type"] . "<br />";

        # 注意 表单字段必须跟数据库表字段名一样
        if (true)
        {
            if ($_FILES["prePicfile"]["error"] > 0)
            {
                echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
            }
            else
            {

                if (file_exists($this->prePicAddr.date("Y-m-d").$_FILES["prePicfile"]["name"]))
                {
                    echo $_FILES["prePicfile"]["name"] . " already exists. ";
                    return;
                }
                else
                {
                    if(!file_exists($this->prePicAddr .'/'.date("Y-m-d")))
                    {
                        mkdir($this->prePicAddr .'/'.date("Y-m-d"));
                    }

                    print_r(WEBROOT .$this->prePicAddr .'/'.date("Y-m-d").'/'. $_FILES["prePicfile"]["name"]);
                    move_uploaded_file($_FILES["prePicfile"]["tmp_name"],
                        WEBROOT. $this->prePicAddr .'/'.date("Y-m-d").'/'.$_POST['goodsNo'].'.rar');


                }
            }
        }
        else
        {
            echo "Invalid file";
        }


        $zip = new ZipArchive();

        if(!file_exists($this->prePicAddr .'/'.date("Y-m-d")))
        {
            mkdir($this->prePicAddr .'/'.date("Y-m-d"));
        }
        $res = $zip->open(  $this->prePicAddr .'/'.date("Y-m-d").'/'. $_POST['goodsNo'].'.rar' );
        if ( $res !== true ) {

            $zip->close();
            return '系统错误:' . $res;
        }

        $msg = $zip->extractTo( WEBROOT . $this->unzipPicAddr .'/'.date("Y-m-d")) ? true : '解压文件失败!';
        $zip->close();


        $goodsNo   = explode(",",$_POST['goodsNo']);
        array_unique($goodsNo);

        foreach($goodsNo as $key=>$val)
        {

            $this->updateGoodsStatus( $goodsNo[$key] ,$this->goodsRight['宝贝原图']);

            /****
             *  STEP2.更新宝贝编辑表，将原图上传的时间以及处理人的信息记录到此表中。
             ***/
            $this->table = 'goodsEdit';
            $rows['idNatureAttr']  = $this->admin['id'];
            $rows['datePhoto']   = date("Y-M-D");
            $this->pk = 'goodsNo';

            if ( $id = $this->find(  array('goodsNo' => $goodsNo[$key])) ) {
                $msg = $this->update( array( 'goodsNo' => $goodsNo[$key] ), $rows ) ? 'success' : 'failed';  //更新供货商
            } else {
                $msg = $this->create( $rows ) ? 'success' : 'failed';                         // 添加供货商
            }


        }

        exit( $msg );


    }


    public function saveEditPrice( $c, $a ) {

        /*
        *   1.更新价格表           priceDescribe
        *   2.更新商品信息表状态   bsInfo
        *   3.更新宝贝编辑表       goodsEdit
        *   4.更新商品自然属性表   natureAttr
        */
        foreach ( $_POST as $key => $val ) {
            $rows[ $key ] = htmlspecialchars(trim( $val ));
        }


        /*
         *   STEP1.更新价格表           priceDescribe
         */

        # 注意 表单字段必须跟数据库表字段名一样

        $goodsNo = explode(",",$rows['goodsNo']);
        $this->table = 'priceDescribe'; // 数据库表名
        $this->pk = 'goodsNo';

        array_unique($goodsNo);

        foreach($goodsNo as $key=>$val)
        {
            $rows1['goodsNo'] =  $val;
            if ( $res = $this->find(array('goodsNo' => $goodsNo[$key])) ) {
                $rows1['lowestPrice'] =$res['costPrice'] + $res['costPrice'] * $rows['lowestPrice']/100 + $rows['lestFloatPrice'];
                $rows1['friendPrice'] = $res['costPrice'] + $res['costPrice'] * $rows['friendPrice']/100 + $rows['friendFloatPrice'];
                $rows1['proSalePrice'] =$res['costPrice'] + $res['costPrice'] * $rows['proSalePrice']/100  + $rows['proSaleFloatPrice'];
                $markPrice[$key]=$rows1['markPrice'] =$res['costPrice'] + $res['costPrice'] * $rows['markPrice']/100  + $rows['markFloatPrice'];
                $msg = $this->update( array( 'goodsNo' =>$goodsNo[$key]), $rows1 ) ? 'success' : 'failed';  //更新供货商
            }
        }

        unset($rows1);
        unset($rows0);


        /*
         *  STEP 2.更新商品信息表状态   bsInfo
         */
        foreach($goodsNo as $key=>$val)
        {
            $this->updateGoodsStatus($val,$this->goodsRight['宝贝定价']);
        }

        /*
        *
        *   STEP3.更新宝贝编辑表       goodsEdit
        */
        $this->table = 'goodsEdit';
        $rows['idPrice'] = $this->admin['id'];
        $rows['datePrice'] = date("Y-M-D");
        $this->pk = 'goodsNo';

        foreach($goodsNo as $key=>$val)
        {
            if ( $id = $this->find(  array('goodsNo' => $val)) ) {
                $msg = $this->update( array( 'goodsNo' => $val ), $rows) ? 'success' : 'failed';  //更新供货商
            } else {
                $msg = $this->create( $rows ) ? 'success' : 'failed';                         // 添加供货商
            }
        }
        /*
         *
         *   STEP4.更新商品自然属性表      natureAttr
         */

        unset($rows);
        $this->table = 'natureAttr';
        foreach($goodsNo as $key=>$val)
        {
            $rows['saleValue']  =  $markPrice[$key];
            if ( $id = $this->find(  array('goodsNo' => $val)) ) {
                $msg = $this->update( array( 'goodsNo' => $val ), $rows) ? 'success' : 'failed';  //更新供货商
            } else {
                $msg = $this->create( $rows ) ? 'success' : 'failed';                         // 添加供货商
            }
        }


        exit($msg);
    }



    public function saveGoodsName( $c, $a ) {

        # 获取表单数据

        $this->table = 'natureAttr'; // 数据库表名

        $goodsNo = explode(",",$_POST['goodsNo']);


        $goodsAttr = array('1'=>'picType','2'=>'thickness','3'=>'flexAttr','4'=>'style','5'=>'brandName','6'=>'clothType');
        $proKey = array('1'=>'反季促销','2'=>'新店开张','3'=>'清仓促销','4'=>'秋冬新品','5'=>'春夏新装','6'=>'包邮促销');


        foreach($goodsNo as $key=>$val)
        {
            $this->pk = 'goodsNo';
            $result = $this->find(array('goodsNo'=>trim($val)));

            $arrayGoodsAttr = $_POST['goodsAttr'] ;
            $name = '';

            foreach($arrayGoodsAttr as  $val1)
            {
                switch($val1)
                {
                    case 1:
                        $name = $name.$this->picType[$result['picType']];
                        break;
                    case 2:
                        $name = $name.$this->thickness[$result['thickness']];
                        break;
                    case 3:
                        $name = $name.$this->flexAttr[$result['flexAttr']];
                        break;
                    case 4:
                        $name = $name.$this->style[$result['style']];
                        break;
                    case 5:
                        $name = $name.$this->brand[$result['brandName']];
                        break;
                    case 6:
                        $name = $name.$this->clothType[$result['clothType']];
                        break;

                    default:
                        break;
                }
            }

            $this->updateGoodsStatus(trim($val),$this->goodsRight['宝贝命名']);


            /**更新宝贝编辑表**/
            $this->table = 'goodsEdit';
            $rows['idName'] = $this->admin['id'];
            $rows['dateName'] = date("Y-M-D");
            $rows['goodsNo'] = trim($val);
            $this->pk = 'goodsNo';

            print_r($rows);
            if ( $id = $this->find(  array('goodsNo' => $rows[ 'goodsNo' ])) ) {
                print_r("541");
                $msg = $this->update( array( 'goodsNo' => $rows['goodsNo'] ), $rows ) ? 'success' : 'failed';  //更新供货商
            } else {
                print_r("542");
                $msg = $this->create( $rows ) ? 'success' : 'failed';                         // 添加供货商
            }

        }


        exit( $msg );

    }

    public function saveEditPostPic( $c, $a ) {

        # 获取表单数据
        foreach ( $_POST as $key => $val ) {
            $rows[ $key ] = htmlspecialchars( trim( $val ) );
        }

        $rows[ 'dateline' ] = strtotime( $rows[ 'dateline' ] );
        unset( $rows[ 'attach' ] );

        print_r($_FILES);

        echo "Type: " . $_FILES["postPicfile"]["type"] . "<br />";

        # 注意 表单字段必须跟数据库表字段名一样
        if (true)
        {
            if ($_FILES["postPicfile"]["error"] > 0)
            {
                echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
            }
            else
            {

                if (file_exists($this->postPicAddr.date("Y-m-d").$_FILES["postPicfile"]["name"]))
                {
                    echo $_FILES["postPicfile"]["name"] . " already exists. ";
                    return;
                }
                else
                {
                    if(!file_exists($this->postPicAddr .'/'.date("Y-m-d")))
                    {
                        mkdir($this->postPicAddr .'/'.date("Y-m-d"));
                    }

                    print_r(WEBROOT .$this->postPicAddr .'/'.date("Y-m-d").'/'. $_FILES["postPicfile"]["name"]);
                    move_uploaded_file($_FILES["postPicfile"]["tmp_name"],
                        WEBROOT. $this->postPicAddr .'/'.date("Y-m-d").'/'.$_POST['goodsNo'].'.rar');


                }
            }
        }
        else
        {
            echo "Invalid file";
        }


        $zip = new ZipArchive();
        print_r("456");

        $res = $zip->open(  $this->postPicAddr .'/'.date("Y-m-d").'/'. $_POST['goodsNo'].'.rar' );
        if ( $res !== true ) {

            print_r("78");
            $zip->close();
            return '系统错误:' . $res;
        }

        print_r("90");
        $msg = $zip->extractTo( WEBROOT . $this->unzipPostPicAddr ) ? true : '解压文件失败!';
        $zip->close();

        $this->updateGoodsStatus($_POST['goodsNo'],$this->goodsRight['处理后图片']);

        print_r("45678");

        /**更新宝贝编辑表**/
        $this->table = 'goodsEdit';
        $rows['idPS'] = $this->admin['id'];
        $rows['datePS'] = date("Y-M-D");
        $this->pk = 'goodsNo';

        if ( $id = $this->find(  array('goodsNo' => $rows[ 'goodsNo' ])) ) {
            print_r("876");
            $msg = $this->update( array( 'goodsNo' => $id['goodsNo'] ), $rows ) ? 'success' : 'failed';  //更新供货商
        } else {
            print_r("543");
            $msg = $this->create( $rows ) ? 'success' : 'failed';                         // 添加供货商
        }

        return $msg;


    }
    public function saveEditOnSaleDes( $c, $a )
    {
        if(!file_exists($this->goodsHtmlAddr .'/'.date("Y-m-d")))
        {
            mkdir($this->goodsHtmlAddr .'/'.date("Y-m-d"));
        }

        /**查询模版文件信息***/

        $sql = "SELECT * FROM xbl_templateinfo WHERE pagePicName IS NOT NULL AND templateId = 1 ORDER BY pagePosition asc ";
        $res = $this->findSql($sql);

        /**创建宝贝描述文件**/
        $file=fopen($this->goodsHtmlAddr .'/'.date("Y-m-d").'/'.$_POST['goodsNo'],"w+") or exit("Unable to open file!");


        fwrite($file,"<table cellSpcing=0 cellPadding=0 width=720 border=0><br/>");


        $j = 0;
        for($t = 0;  $t<count($res); $t++)
        {
            fwrite($file,"<tr><TD> <img src = " .'"' .$res[$t]['pagePicUrl'].'"'." width = 720> </td></tr>");
            if(1 == $res[$t]['pagePicFlag'])
            {
                for($i = 0 ; $i < 4; $i++)
                {
                    print_r($_POST["pic$j$i"]);
                    if(''!=$_POST["pic$j$i"])
                        fwrite($file,"<tr><td> <img src = " .'"' .$_POST["pic$j$i"].'"'." width = 720> </td></tr><br/>");
                }
                $j++;
            }

        }

        fwrite($file,"</table>");
        fclose($file);

        $this->updateGoodsStatus($_POST['goodsNo'],$this->goodsRight['宝贝描述']);

        /**更新宝贝编辑表**/
        $this->table = 'goodsEdit';
        $rows['idgoodEidt'] = $this->admin['id'];
        $rows['dateGoodsEdit'] = date("Y-M-D");
        $this->pk = 'goodsNo';

        if ( $id = $this->find(  array('goodsNo' => $rows[ 'goodsNo' ])) ) {
            $msg = $this->update( array( 'goodsNo' => $id['goodsNo'] ), $rows ) ? 'success' : 'failed';  //更新供货商
        } else {
            $msg = $this->create( $rows ) ? 'success' : 'failed';                         // 添加供货商
        }




    }
    public function saveEditClothSize( $c, $a ) {

        /*
        foreach ( $_POST as $key => $val ) {
                $rows[ $key ] = htmlspecialchars( trim( $val ) );
            }

        $this->table = 'clothSize'; // 数据库表名
        if ( $id = intval( G( "id" ) ) ) {
            $msg = $this->update( array( 'id' => $id ), $rows ) ? 'success' : 'failed';  //更新供货商
        } else {
            $msg = $this->create( $rows ) ? 'success' : 'failed';                         // 添加供货商
        }*/
        $i = 0;
        $this->table = 'clothSize'; // 数据库表名
        $rows['goodsNo'] = $_POST['goodsNo'];
        $rows['templateId'] = $_POST['templateId'];

        while($_POST["heightLen$i"])
        {
            $rows['heightLen'] = $_POST["heightLen$i"];
            $rows['size1'] = $_POST["size1$i"];
            $rows['size2'] = $_POST["size1$i"];
            $rows['size3'] = $_POST["size1$i"];
            $rows['size4'] = $_POST["size1$i"];
            $rows['size5'] = $_POST["size1$i"];
            $rows['size6'] = $_POST["size1$i"];


            $msg = $this->create( $rows ) ? 'success' : 'failed';
            $i++;
            if($i > 10)
                break;
        }


        $this->updateGoodsStatus( $rows['goodsNo'],$this->goodsRight['宝贝尺寸']);

        /**更新宝贝编辑表**/
        $this->table = 'goodsEdit';
        $rows['idSize'] = $this->admin['id'];
        $rows['dateSize'] = date("Y-M-D");
        $this->pk = 'goodsNo';

        if ( $id = $this->find(  array('goodsNo' => $rows[ 'goodsNo' ])) ) {
            $msg = $this->update( array( 'goodsNo' => $id['goodsNo'] ), $rows ) ? 'success' : 'failed';  //更新供货商
        } else {
            $msg = $this->create( $rows ) ? 'success' : 'failed';                         // 添加供货商
        }

    }







}